const os = require('os');
const lodash = require('lodash');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const paths = require('../paths');
const cpaasConfig = paths.getCpaasBootConfig(paths.appPath) || {};

// 根模块路径
const isWindow = os.platform() === 'win32';
const sep = isWindow ? '\\\\' : path.sep;
// 指定那些模块加 css modules
const projectReg = cpaasConfig.projectReg || '(cpaas-front)(-([\\w-]*))?';
// const mayDepProjectReg = `${projectReg}(node_modules${sep}${projectReg})?`;
// const cpaasRootIndexReg = new RegExp(`${rootPath}${sep}src${sep}index\\.less`);
const cpaasIndexReg = new RegExp(
  `${sep}(node_modules|packages)${sep}${projectReg}${sep}(lib|src)${sep}index\\.less`
);
// const cpaasRootModuleReg = new RegExp(`${rootPath}${sep}src${sep}(.*)\\.less`);
const cpaasModuleReg = new RegExp(
  `${sep}(node_modules|packages)${sep}${projectReg}${sep}(lib|src)${sep}(.*)\\.less`
);
const cpaasModuleModuleIndex = 4;
const cpaasModulePathIndex = 6;

// common function to get style loaders
const getStyleLoaders = ({
  cssOptions,
  preProcessor,
  preProcessorOptions,
  styleOptions,
  isEnvDevelopment,
  shouldUseRelativeAssetPaths,
  publicPath,
}) => {
  const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
  const isEnvProduction = !isEnvDevelopment;
  const loaders = [
    isEnvDevelopment && {
      loader: require.resolve('style-loader'),
      options: styleOptions,
    },
    isEnvProduction && {
      loader: MiniCssExtractPlugin.loader,
      options: Object.assign(
        {},
        shouldUseRelativeAssetPaths
          ? { publicPath: '../../' }
          : {
              publicPath: publicPath,
            }
      ),
    },
    {
      loader: require.resolve('css-loader'),
      options: {
        // modules: true,
        getLocalIdent: (context, _, localName) => {
          const filename = context.resourcePath;
          if (cpaasIndexReg.test(filename)) {
            return localName;
          } else if (cpaasModuleReg.test(context.resourcePath)) {
            const m = context.resourcePath.match(cpaasModuleReg);
            const mm = m[cpaasModuleModuleIndex] || ''; // module
            const pt = m[cpaasModulePathIndex]; // path
            return lodash.kebabCase(mm + '-' + pt + '-' + localName);
          } else {
            return localName;
          }
        },
        ...cssOptions,
      },
    },
    {
      // Options for PostCSS as we reference these options twice
      // Adds vendor prefixing based on your specified browser support in
      // package.json
      loader: require.resolve('postcss-loader'),
      options: {
        // Necessary for external CSS imports to work
        // https://github.com/facebook/create-react-app/issues/2677
        ident: 'postcss',
        plugins: () => [
          require('postcss-flexbugs-fixes'),
          require('postcss-preset-env')({
            autoprefixer: {
              flexbox: 'no-2009',
            },
            stage: 3,
          }),
        ],
        sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
      },
    },
  ].filter(Boolean);
  if (preProcessor) {
    loaders.push({
      loader: require.resolve(preProcessor),
      options: {
        sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
        ...preProcessorOptions,
      },
    });
  }
  return loaders;
};

module.exports = getStyleLoaders;
